import { createRouter, createWebHistory } from 'vue-router';
// 预先导入可能出现问题的组件
import HomeworkSubmit from '../views/student/HomeworkSubmit.vue';
import HomeworkDetail from '../views/student/HomeworkDetail.vue';
import { ElMessage } from 'element-plus';

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue'),
    meta: { title: '登录', requiresAuth: false }
  },
  // 学生相关路由
  {
    path: '/student',
    name: 'StudentLayout',
    component: () => import('../views/student/Layout.vue'),
    redirect: '/student/dashboard',
    meta: { requiresAuth: true, role: 'student' },
    children: [
      {
        path: 'dashboard',
        name: 'StudentDashboard',
        component: () => import('../views/student/Dashboard.vue'),
        meta: { title: '学生主页', requiresAuth: true, role: 'student' }
      },
      {
        path: 'homework',
        name: 'StudentHomework',
        component: () => import('../views/student/HomeworkList.vue'),
        meta: { title: '我的作业', requiresAuth: true, role: 'student' }
      },
      {
        path: 'homework-detail/:id',
        name: 'HomeworkDetail',
        component: HomeworkDetail,
        meta: { title: '作业详情', requiresAuth: true, role: 'student' }
      },
      {
        path: 'homework-submit/:id',
        name: 'HomeworkSubmit',
        component: HomeworkSubmit,
        meta: { title: '提交作业', requiresAuth: true, role: 'student' }
      },
      {
        path: 'messages',
        name: 'StudentMessages',
        component: () => import('../views/student/MessageCenter.vue'),
        meta: { title: '消息中心', requiresAuth: true, role: 'student' }
      },
      {
        path: 'profile',
        name: 'StudentProfile',
        component: () => import('../views/student/Profile.vue'),
        meta: { title: '个人信息', requiresAuth: true, role: 'student' }
      }
    ]
  },
  // 教师相关路由
  {
    path: '/teacher',
    name: 'TeacherLayout',
    component: () => import('../views/teacher/Layout.vue'),
    redirect: '/teacher/dashboard',
    meta: { requiresAuth: true, role: 'teacher' },
    children: [
      {
        path: 'dashboard',
        name: 'TeacherDashboard',
        component: () => import('../views/teacher/Dashboard.vue'),
        meta: { title: '教师主页', requiresAuth: true, role: 'teacher' }
      },
      {
        path: 'homework',
        name: 'TeacherHomework',
        component: () => import('../views/teacher/HomeworkManage.vue'),
        meta: { title: '作业管理', requiresAuth: true, role: 'teacher' }
      },
      {
        path: 'messages',
        name: 'TeacherMessages',
        component: () => import('../views/teacher/MessageCenter.vue'),
        meta: { title: '消息中心', requiresAuth: true, role: 'teacher' }
      },
      {
        path: 'profile',
        name: 'TeacherProfile',
        component: () => import('../views/teacher/Profile.vue'),
        meta: { title: '个人信息', requiresAuth: true, role: 'teacher' }
      }
    ]
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('../views/NotFound.vue'),
    meta: { title: '页面不存在' }
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 路由前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 在线教育平台` : '在线教育平台';

  try {
    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo');
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null;
    const loginTime = localStorage.getItem('loginTime');
    const currentTime = new Date().getTime();

    // 检查登录时间，如果超过24小时或未设置登录时间，则清除登录信息
    const isLoginExpired = !loginTime || (currentTime - parseInt(loginTime)) > 24 * 60 * 60 * 1000;

    if (isLoginExpired && userInfo) {
      // 清除过期的登录信息
      localStorage.removeItem('userInfo');
      localStorage.removeItem('loginTime');
      ElMessage.warning('登录已过期，请重新登录');
      next({ name: 'Login' });
      return;
    }

    // 检查是否需要认证
    if (to.meta.requiresAuth) {
      if (!userInfo) {
        // 未登录，跳转到登录页
        ElMessage.warning('请先登录');
        next({ name: 'Login' });
      } else if (to.meta.role && to.meta.role !== userInfo.role) {
        // 角色不匹配
        ElMessage.warning(`无权访问${to.meta.role === 'student' ? '学生' : '教师'}页面`);
        next({ path: `/${userInfo.role}/dashboard` });
      } else {
        next();
      }
    } else {
      // 如果是根路径或登录页
      if (to.path === '/' || to.path === '/login') {
        // 如果已登录且未过期，根据角色重定向到对应的首页
        if (userInfo && !isLoginExpired) {
          next({ path: `/${userInfo.role}/dashboard` });
        } else {
          // 未登录或登录过期，正常前往登录页
          next();
        }
      } else {
        next();
      }
    }
  } catch (error) {
    console.error('路由守卫错误:', error);
    // 发生错误时，清除可能损坏的用户数据并重定向到登录页
    localStorage.removeItem('userInfo');
    localStorage.removeItem('loginTime');
    next({ name: 'Login' });
  }
});

export default router;
